﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using OpticalPowerMeter.UserControls;
using System.Text.RegularExpressions;

namespace OpticalPowerMeter
{
    /// <summary>
    /// LinearGroupWindow.xaml 的交互逻辑
    /// </summary>
    public partial class LinearGroupWindow : Window
    {
        public LinearGroupWindow()
        {
            InitializeComponent();
            InitGroupList();
        }

        #region 绑定显示的属性
        //清单表头字号
        static DependencyProperty DataGridHeadFontProperty = DependencyProperty.Register(
            "DataGridHeadFont",
            typeof(double),
            typeof(LinearGroupWindow)
            );

        //单元字号
        static DependencyProperty CellFontProperty = DependencyProperty.Register(
            "CellFont",
            typeof(double),
            typeof(LinearGroupWindow)
            );

        //单元高度
        static DependencyProperty CellHeightProperty = DependencyProperty.Register(
            "CellHeight",
            typeof(double),
            typeof(LinearGroupWindow)
            );

        //数据列宽
        static DependencyProperty DataGridColumnWidthProperty = DependencyProperty.Register(
            "DataGridColumnWidth",
            typeof(double),
            typeof(LinearGroupWindow)
            );

        //线性组字号
        static DependencyProperty GroupNameFontSizeProperty = DependencyProperty.Register(
            "GroupNameFontSize",
            typeof(double),
            typeof(LinearGroupWindow)
            );

        //线性组输入框高度
        static DependencyProperty GroupNameBoxHeightProperty = DependencyProperty.Register(
            "GroupNameBoxHeight",
            typeof(double),
            typeof(LinearGroupWindow)
            );

        //线性组输入框宽度
        static DependencyProperty GroupNameBoxWidthProperty = DependencyProperty.Register(
            "GroupNameBoxWidth",
            typeof(double),
            typeof(LinearGroupWindow)
            );

        //线性组输入框边距
        static DependencyProperty GroupNameBoxMarginProperty = DependencyProperty.Register(
            "GroupNameBoxMargin",
            typeof(Thickness),
            typeof(LinearGroupWindow)
            );

        //保存按钮的边距
        static DependencyProperty SaveButtonMarginProperty = DependencyProperty.Register(
            "SaveButtonMargin",
            typeof(Thickness),
            typeof(LinearGroupWindow)
            );

        //删除按钮的边距
        static DependencyProperty DeleteButtonMarginProperty = DependencyProperty.Register(
            "DeleteButtonMargin",
            typeof(Thickness),
            typeof(LinearGroupWindow)
            );

        //线性点输入框宽度
        static DependencyProperty LinearWidthProperty = DependencyProperty.Register(
            "LinearWidth",
            typeof(double),
            typeof(LinearGroupWindow)
            );
        #endregion


        //尺寸发生变化时，调整控件尺寸
        private void Size_Changed(object sender, SizeChangedEventArgs args)
        {
            #region 刷新左侧机型列表字号等内容
            Grid parentGrid = (Grid)LinearGroupDataGrid.Parent;
            double parentWidth = parentGrid.ActualWidth;
            LinearGroupDataGrid.Width = parentWidth;
            double dataGridWidth = parentWidth;
            SetValue(DataGridColumnWidthProperty, dataGridWidth);  //设置列宽
            double height = dataGridWidth / 5; //宽度与高度比5:1
            double headFontSize = Math.Round((height - 10) / 1.27, 1);  //head字号
            SetValue(DataGridHeadFontProperty, headFontSize);
            SetValue(CellFontProperty, headFontSize - 2); //内容比head小2个字号
            SetValue(CellHeightProperty, Math.Round((headFontSize - 2) * 1.27, 1));
            #endregion
            #region 刷新线性组部分字号及边距等
            double productNameGridWidth = GroupNameGrid.ActualWidth;
            double productNameFontSize = Math.Round((productNameGridWidth * 0.3 - 10) / 4, 1);  //线性组名称占总宽度30%
            SetValue(GroupNameFontSizeProperty, productNameFontSize);
            double productNameBoxWidth = Math.Round(productNameGridWidth * 0.7 - 20, 1);
            double productNameBoxHeight = Math.Round(productNameFontSize * 1.27);
            SetValue(GroupNameBoxHeightProperty, productNameBoxHeight); //线性组名输入框的尺寸
            SetValue(GroupNameBoxWidthProperty, productNameBoxWidth);
            double boxLeft = Math.Round(productNameGridWidth * 0.3 + 10, 1);
            SetValue(GroupNameBoxMarginProperty, new Thickness(boxLeft, 0, 0, 0));
            #endregion
            #region 刷新按钮部分边距
            double saveButtonLeft = Math.Round(productNameGridWidth / 5, 1);
            SetValue(SaveButtonMarginProperty, new Thickness(saveButtonLeft, 0, 0, 0));
            double deleteButtonLeft = Math.Round(productNameGridWidth / 5 * 3, 1);
            SetValue(DeleteButtonMarginProperty, new Thickness(deleteButtonLeft, 0, 0, 0));
            #endregion
            SetValue(LinearWidthProperty, productNameGridWidth);
        }

        //线性点设置的"+"、"-"号点击时
        private void Linear_Click(object sender , ButtonClickEventArgs args) {
            LinearControl linearControl = sender as LinearControl;
            double linearHeight = linearControl.ActualHeight;  //控件高度
            double linearWidth = linearControl.ActualWidth;//控件宽度
            Thickness linearMargin = linearControl.Margin;
            UIElementCollection uIElementCollection = LinearGrid.Children;
            int index = uIElementCollection.IndexOf(linearControl); //当前控件在列表中的位置
            string buttonName = args.ButtonName;
            if (buttonName.Equals("AddButton")) //增加控件
            {
                #region 将当前控件下面的控件下移
                for (int i = index + 1; i < uIElementCollection.Count; i++)
                {
                    LinearControl currentLinear = (LinearControl)uIElementCollection[i];
                    Thickness currentMargin = currentLinear.Margin;
                    double cuurrentLeft = currentMargin.Left;
                    double currentTop = currentMargin.Top;
                    double currentRight = currentMargin.Right;
                    double currentBottom = currentMargin.Bottom;
                    currentLinear.Margin = new Thickness(cuurrentLeft,currentTop+linearHeight,currentRight,currentBottom);
                }
                #endregion
                #region 在当前控件下面添加一个LinearControl
                LinearControl newLinearControl = new LinearControl();
                newLinearControl.Height = linearHeight;
                newLinearControl.Width = linearWidth;
                newLinearControl.HorizontalAlignment = HorizontalAlignment.Left;
                newLinearControl.VerticalAlignment = VerticalAlignment.Top;
                newLinearControl.LinearClick += new EventHandler<ButtonClickEventArgs>(Linear_Click);
                uIElementCollection.Insert(index + 1, newLinearControl);
                double linearLeft = linearMargin.Left;
                double linearTop = linearMargin.Top;
                double linearRight = linearMargin.Right;
                double linearBottom = linearMargin.Bottom;
                newLinearControl.Margin = new Thickness(linearLeft, linearTop+linearHeight,linearRight,linearBottom);
                #endregion
            }
            else //删除控件
            {
                #region 至少保留一个控件
                if (uIElementCollection.Count == 1)
                {
                    return;
                }
                #endregion
                uIElementCollection.RemoveAt(index); //移除当前控件
                #region 把当前控件下面的控件上移
                for (int i = index; i < uIElementCollection.Count; i++)
                {
                    LinearControl currentLinear = (LinearControl)uIElementCollection[i];
                    Thickness currentMargin = currentLinear.Margin;
                    double cuurrentLeft = currentMargin.Left;
                    double currentTop = currentMargin.Top;
                    double currentRight = currentMargin.Right;
                    double currentBottom = currentMargin.Bottom;
                    currentLinear.Margin = new Thickness(cuurrentLeft, currentTop - linearHeight, currentRight, currentBottom);
                }
                #endregion
            }
        }

        //点击左侧线性组名称时，刷新右侧相应信息
        private void LinearGroupDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            string groupName = LinearGroupDataGrid?.SelectedValue?.ToString().Trim();
            if (groupName == null || groupName == "")
            {
                return;
            }
            GroupNameTextBox.Text = groupName;
            List<LinearPoint> linearPoints = LinearGroupManagement.GetIntance().GetLinearList(groupName);
            LinearControl linearControl = (LinearControl)LinearGrid.Children[0]; //获取第一个控件
            double linearWidth = linearControl.ActualWidth;
            double linearHeight = linearControl.ActualHeight;
            double left = linearControl.Margin.Left;
            double right = linearControl.Margin.Right;
            double bottom = linearControl.Margin.Bottom;
            LinearGrid.Children.Clear();
            for (int i=0;i<linearPoints.Count;i++) {
                int index = linearPoints[i].Index;
                double p1 = linearPoints[i].P1;
                double p2 = linearPoints[i].P2;
                LinearControl newControl = new LinearControl();
                newControl.HorizontalAlignment = HorizontalAlignment.Left;
                newControl.VerticalAlignment = VerticalAlignment.Top;
                newControl.Height = linearHeight;
                newControl.Width = linearWidth;
                newControl.ToolTip = $"档位={index}";
                newControl.P1 = p1 + "";
                newControl.P2 = p2 + "";
                newControl.LinearClick += Linear_Click;
                newControl.Margin = new Thickness(left,i*linearHeight,right,bottom);
                LinearGrid.Children.Add(newControl);
            }
        }

        //保存按钮点击时
        private void SaveButton_Click(object sender, RoutedEventArgs args)
        {
            string groupname = GroupNameTextBox.Text.Trim();
            if (groupname == "")
            {
                MessageBox.Show("线性组名为空，无法添加", "无法添加空线性组", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            #region 获取线性点清单，放入一个List
            List<LinearPoint> linearList = new List<LinearPoint>();
            foreach(UIElement uIElement in LinearGrid.Children)
            {
                if (!uIElement.GetType().Name.EndsWith("LinearControl")) {
                    continue;
                }
                LinearControl linearControl = uIElement as LinearControl;
                string p1String = linearControl.P1?.Trim();
                string p2String = linearControl.P2?.Trim();
                if (p1String == null || p2String == null) {
                    continue;
                }
                string pattern = @"^[-+]?[0-9]+\.{0,1}[0-9]*$";
                if (!(Regex.IsMatch(p1String, pattern) && Regex.IsMatch(p2String, pattern))) //如果输入不是一个数字，则认为是无效数据
                {
                    continue;
                }
                double p1 = Convert.ToDouble(p1String);
                double p2 = Convert.ToDouble(p2String);
                int index = 0;
                if(p1<=10 && p1 >= 0)
                {
                    index = 0;
                }else if (p1<0 && p1>=-10) {
                    index = 1;
                }else if(p1<-10 && p1 >= -20)
                {
                    index = 2;
                }else if(p1<-20 && p1 >= -30)
                {
                    index = 3;
                }else if(p1<-30 && p1 >= -40)
                {
                    index = 4;
                }else if(p1<-40 && p1 >= -50)
                {
                    index = 5;
                }else if(p1<-50 && p1>= -60)
                {
                    index = 6;
                }
                else
                {
                    index = 7;
                }
                LinearPoint linearPoint= new LinearPoint();
                linearPoint.Index = index;
                linearPoint.P1 = p1;
                linearPoint.P2 = p2;
                linearList.Add(linearPoint);
            }
            #endregion
            LinearGroupManagement.GetIntance().SaveGroups(groupname,linearList);
            MessageBox.Show("保存线性组" + groupname + "完成", "保存完成", MessageBoxButton.OK, MessageBoxImage.Information);
            //刷新列表
            InitGroupList();
        }

        //删除按钮点击时
        private void DeleteButton_Click(object sender, RoutedEventArgs args)
        {
            string groupname = GroupNameTextBox.Text.Trim();
            if (groupname == "")
            {
                return;
            }
            MessageBoxResult clickButton = MessageBox.Show("是否确定要删除" + groupname, "删除线性组", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (clickButton == MessageBoxResult.Yes)
            {
                LinearGroupManagement.GetIntance().DeleteGroup(groupname);
            }
            //刷新列表
            InitGroupList();
        }

        //刷新列表
        private void InitGroupList()
        {
            List<string> groupNameList = LinearGroupManagement.GetIntance().GetLinearGroupNameList();
            LinearGroupDataGrid.ItemsSource = null;
            LinearGroupDataGrid.ItemsSource = groupNameList;
        }
    }
}
